package com.lpf.json.serializable;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.lpf.json.serializable.annotation.LongToStr;
import com.lpf.json.serializable.enums.Type;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.lang.reflect.Field;

@JsonComponent
public class JacksonConfiguration01 {

    public static class DateFormatSerializer extends JsonSerializer<McSerializable> {
        @Override
        public void serialize(McSerializable serializable, JsonGenerator generator, SerializerProvider serializers) throws IOException {
            try {
                generator.writeStartObject();

                Field[] fields = serializable.getClass().getDeclaredFields();
                boolean flag;

                for (Field field : fields) {
                    field.setAccessible(true);
                    flag = dealLongToStr(serializable, field, generator);
                    if (!flag) {
                        String name = field.getName();
                        Object value = field.get(serializable);
                        generator.writeObjectField(name, value);
                    }
                }

                generator.writeEndObject();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        private boolean dealLongToStr(McSerializable serializable, Field field, JsonGenerator generator) throws IOException, IllegalAccessException {
            if (field.isAnnotationPresent(LongToStr.class)) {
                String name = field.getName();
                Object value = field.get(serializable);
                LongToStr annotation = field.getAnnotation(LongToStr.class);

                Type type = annotation.value();
                if (type == Type.ADDSTR) {
                    generator.writeObjectField(name, value);
                    generator.writeObjectField(name + "Str", value.toString());
                    return true;
                }
                if (type == Type.ORIGINAL) {
                    generator.writeObjectField(name, value.toString());
                    return true;
                }
            }
            return false;
        }
    }

    public static class DateParseDeserializer extends JsonDeserializer<McSerializable> {
        @Override
        public McSerializable deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            System.out.println("----------------------");
            String valueAsString = p.getValueAsString();
            return null;
        }
    }
}
